<template>
  <div>
    <bcd-top title="产品详情" englishtitle="PRODUCTS DETAIL" />
    <div
      class="proInfo"
      :style="$store.getters.screenWidth ? 'display:flex;flex-direction: column;' : '' "
    >
      <div style="width:600px" :style="$store.getters.screenWidth ? 'width:100%' : '' ">
        <div
          style="width:100%;height:600px;"
          :style="$store.getters.screenWidth ? 'height:300px' : '' "
        >
          <el-carousel
            style="width:100%;height:100%"
            indicator-position="none"
            :autoplay="false"
            ref="carousel"
          >
            <el-carousel-item v-if="video">
              <video-player
                class="video-player vjs-custom-skin"
                ref="videoPlayer"
                :playsinline="true"
                :options="playerOptions"
                style="width:100%;height:100%"
              ></video-player>
            </el-carousel-item>
            <el-carousel-item
              style="width:100%;height:100%;background-color: #fff;"
              v-for="(item,index) in sliderArr"
              :key="index"
            >
              <img
                :src="item"
                style="width:600px;height:600px"
                :style="$store.getters.screenWidth ? 'width:100%;height:300px' : '' "
                alt
              />
            </el-carousel-item>
          </el-carousel>
        </div>
        <div
          style="max-width:100%;display:flex;margin-top:10px;overflow-x:scroll;overflow-y:hidden;"
          :style="$store.getters.screenWidth ? 'width:100%' : '' "
        >
          <div
            style="width:100px;margin-right:10px; flex-shrink: 0;"
            v-if="video"
            @click="chooseItem('video')"
          >
            <img :src="sliderArr[0]" style="width:100%;height:100px" alt />
          </div>

          <div
            style="width:100px;margin-right:10px;height:100px;  flex-shrink: 0;"
            v-for="(item,index) in sliderArr"
            :key="index"
            @click="chooseItem(index)"
          >
            <img :src="item" style="width:100%;height:100px" alt />
          </div>
        </div>
      </div>

      <div
        style="padding:10px;flex:1;padding-left:20px"
        :style="$store.getters.screenWidth ? 'width:100%' : '' "
      >
        <div class="product_name">{{pInfo.storeName}}</div>
        <div class="product_price">
          <span style="font-size:18px">￥</span>
          <span style="font-size:30px">{{pInfo.price || 0}}</span>
        </div>
        <template v-if="spec">
          <div class="product_posteg" v-for="(item,index) in spec.items" :key="index">
            <div class="left_posteg">{{item.value}}</div>
            <div style="display:flex;flex-wrap:wrap;">
              <div
                class="shopdiscuount"
                @click="chooseLable(item,item1)"
                v-for="(item1,index) in item.valuecheck"
                :key="index"
                :class="item1.check ? 'checked' : ''"
                style="padding:3px 8px"
              >{{item1.name}}</div>
            </div>
          </div>
        </template>
        <div class="product_posteg">
          <div class="left_posteg">数量</div>
          <el-input-number v-model="num" :min="1" :max="50" label="描述文字"></el-input-number>
        </div>
        <div class="product_posteg">
          <div class="left_posteg">库存</div>
          <div style="font-size:15px;color:#76838f;margin-bottom:10px">{{pInfo.stock}}件</div>
        </div>
        <div style="display:flex">
          <el-button type="warning" @click="addCart">加入购物车</el-button>
          <el-button type="danger" :loading="buyLoading" @click="buyNow">立即购买</el-button>
        </div>
      </div>
    </div>
    <div class="picDetail">
      <div class="detail_tezt">
        <span
          style="margin-bottom:5px;
    padding-bottom: 9px;
    border-bottom: 2px solid #62a8ea;"
        >商品详情</span>
      </div>
      <span v-html="pInfo.storeInfo"></span>
    </div>
    <footer-part></footer-part>
    <el-dialog
      title="请选择付款方式"
      :visible.sync="dialogVisible"
      width="300px"
      :before-close="handleClose"
    >
      <div>
        <vue-qr :text="payUrl" :size="240"></vue-qr>
      </div>
    </el-dialog>

    <!-- 收货地址 -->
    <el-dialog
      @close="addressClose"
      destroy-on-close
      title="收货地址"
      width="300px"
      :visible.sync="dialogFormVisibleAddress"
    >
      <el-form ref="addressForm" :model="form">
        <el-form-item
          prop="name"
          :rules=" { required: true, message: '请输入收货人姓名', trigger: 'blur' }"
        >
          <el-input style="width:100%" v-model="form.name" autocomplete="off" placeholder="收货人姓名"></el-input>
        </el-form-item>
        <el-form-item
          prop="phone"
          :rules=" { required: true, message: '请输入收货人电话', trigger: 'blur' }"
        >
          <el-input style="width:100%" v-model="form.phone" autocomplete="off" placeholder="收货人电话"></el-input>
        </el-form-item>
        <el-form-item
          prop="provice"
          :rules=" { required: true, message: '请选择省市', trigger: 'blur' }"
        >
          <el-cascader
            style="width:100%"
            :options="options"
            v-model="form.provice"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          prop="address"
          :rules=" { required: true, message: '请输入详细地址', trigger: 'blur' }"
        >
          <el-input
            style="width:100%"
            type="textarea"
            v-model="form.address"
            autocomplete="off"
            placeholder="详细地址"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cofirmAddress">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { provinceAndCityData, CodeToText } from "element-china-area-data";
import vueQr from "vue-qr";
import {
  productDetail,
  addCart,
  buyNow,
  orderAdd,
  unifiedorder,
  addressList,
  cartList,
  openIdGet
} from "../api/api";
import bcdTop from "../components/bcdTop";
import footerPart from "../views/footer";
import { videoPlayer } from "vue-video-player";
import "video.js/dist/video-js.css";
import axios from "axios";
// , productDetailPic
export default {
  data() {
    return {
      checked: true,
      attrIndex: 0,
      spec: {},
      options: provinceAndCityData,
      selectedOptions: [],
      form: {
        name: "",
        phone: "",
        address: "",
        provice: ""
      },
      address: "",
      dialogFormVisibleAddress: false,
      buyLoading: false,
      id: "",
      pInfo: {},
      num: 1,
      cartIds: null,
      sliderArr: [],
      video: "",
      dialogVisible: false,
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: true, // 如果为true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: true, // 是否视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: "video/mp4", // 类型
            src: "" // url地址
          }
        ],
        poster: "", // 封面地址
        notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: false, // 是否显示剩余时间功能
          fullscreenToggle: true // 是否显示全屏按钮
        }
      },
      radio3: "1",
      payUrl: "",
      label: []
    };
  },
  components: {
    bcdTop,
    footerPart,
    videoPlayer,
    vueQr
  },
  computed: {
    specArr(val) {
      return this.spec;
    }
  },
  created() {
    if (this.$route.query.code) {
      openIdGet({
        code: this.$route.query.code
      })
        .then(res => {
          window.sessionStorage.setItem("openId", res.data.openId);
        })
        .catch(err => {});
    }
  },
  mounted() {
    // let arr = [
    //   [1, 2, 3],
    //   [2, 3, 4],
    //   [3, 4, 5],
    //   [4, 5, 6]
    // ];
    // let newarr = [];
    // arr[0].forEach((o,index) => {
    //   let p = [];
    //   arr.forEach((e, index1, ary) => {
    //     p.push(e[index]);
    //   });
    //   newarr.push(p)
    // });
    // console.log("newarr", newarr);
    // return;
    this.id = this.$route.query.userId;
    this.getinfo();
  },

  methods: {
    //计算价格
    calcutePrice() {
      console.log("12www", this.spec.attrs, this.label);

      this.spec.attrs.forEach((e, arr) => {
        if (e.values.join(",") == this.label.join(",")) {
          this.pInfo.price = e.price;
          this.pInfo.stock = e.stock;
        }
      });
    },
    chooseLable(item, item1) {
      this.spec.items.forEach(e => {
        if (item.value == e.value) {
          e.valuecheck.forEach(ele => {
            if (ele.name == item1.name) {
              ele.check = true;
            } else {
              ele.check = false;
            }
          });
        }
      });
      this.label = [];
      this.spec.items.forEach(e => {
        e.valuecheck.forEach(ele => {
          if (ele.check) {
            this.label.push(ele.name);
          }
        });
      });
      this.calcutePrice();
      return;
    },
    cofirmAddress() {
      this.$refs.addressForm.validate(async valid => {
        if (valid) {
          const resOrder = await orderAdd({
            cartIds: this.cartIds,
            couponId: null,
            couponPrice: null,
            deductionPrice: null,
            expressDump: null,
            freightFree: 0,
            mark: null,
            payPostage: 0,
            payPrice: this.pInfo.price,
            province: "anhui",
            realName: this.form.name,
            totalNum: this.num,
            totalPostage: 0,
            totalPrice: Number(this.pInfo.price) * Number(this.num),
            uid: this.$store.getters["userId"],
            userAddress: this.address,
            userPhone: this.form.phone
          });
          const urlPay = await unifiedorder({
            id: resOrder.data
          });
          this.payUrl = urlPay.data.code_url;
          this.dialogVisible = true;
          this.dialogFormVisibleAddress = false;
        } else {
          return false;
        }
      });
    },
    addressClose() {
      this.$refs["addressForm"].resetFields();
    },
    handleChange(value) {
      var ctt = CodeToText[value[0]] + CodeToText[value[1]];
      this.address = ctt;
    },
    async getinfo() {
      let info = await productDetail({ id: this.id });
      this.pInfo = info.data;
      this.pInfo.storeInfo = this.pInfo.storeInfo.replace(
        /<img/g,
        '<img style="max-width:100%;height:auto"'
      );
      this.video = info.data.videoLink;
      // this.video = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
      this.playerOptions.sources[0].src = info.data.videoLink;
      // "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
      this.sliderArr = info.data.sliderImage.split(",");
      this.spec = JSON.parse(info.data.spec);
      console.log("121212", this.spec);
      if (this.spec) {
        this.spec.attrs.forEach(e => {
          e.detail = JSON.parse(e.detail);
        });
        // let infoPic = await productDetailPic({id:this.id})
        this.spec.items.forEach((e, arr) => {
          let p = [];
          e.detail.forEach((ele, index, arr) => {
            p.push({
              name: ele,
              check: index == 0 ? true : false
            });
          });
          this.label.push(e.detail[0]);
          this.$set(e, "valuecheck", p);
        });
        this.calcutePrice();
      }
    },
    handleClose() {
      this.dialogVisible = false;
    },
    async buyNow() {
      if (!this.$store.getters["userId"]) {
        this.$notify({
          type: "error",
          title: "请先登录"
        });
        return;
      }
      if (this.num > this.pInfo.stock) {
        this.$notify({
          type: "error",
          title: "失败",
          message: "库存不足！"
        });
        return;
      }
      //判断是否存在openid

      if (
        !window.sessionStorage.getItem("openId") &&
        this.$store.getters.screenWidth
      ) {
        this.$notify({
          title: "授权中",
          message: "正在获取微信授权，页面将刷新",
          type: "success"
        });
        setTimeout(() => {
          window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc2420316b9a7dec0&redirect_uri=http%3A%2F%2Fwww.ramboat.cn%2FproductDetail?userId=${this.id}&response_type=code&scope=snsapi_base&state=STATE#wechat_re`;
        }, 1000);
        return;
      }
      const { data } = await addressList({
        uid: this.$store.getters["userId"]
      });
      //判断是否有地址
      // if (data.length == 0) {
      //   setTimeout(() => {
      //     this.$notify({
      //       title: "请先添加收货地址",
      //       type: "error"
      //     });
      //     this.isLoading = false;
      //     this.$router.push("/address");
      //   }, 500);
      //   return;
      // }
      let p;
      this.buyLoading = true;
      if (this.spec) {
        p = JSON.parse(JSON.stringify(this.spec));
        let a = [];
        p.attrs.forEach((e, index, arr) => {
          if (e.values.join(",") == this.label.join(",")) {
            a.push(e);
          }
        });
        p.attrs = a;
        p.attrs.forEach(e => {
          e.detail = JSON.stringify(e.detail);
        });
      }

      const cart = await addCart({
        cartNum: this.num,
        productAttrId: 0,
        productId: this.id,
        uid: this.$store.getters["userId"],
        spec: this.spec ? JSON.stringify(p) : null
      });
      this.cartIds = cart.data;
      const res = await cartList({
        uid: this.$store.getters["userId"]
      });
      let q = [];
      res.data.forEach(e => {
        if (e.id == cart.data) {
          q.push(e);
        }
      });
      this.buyLoading = false;
      this.$router.push({
        path: "/pay",
        query: { paArr: JSON.stringify(q) }
      });
      return;
    },
    async addCart() {
      if (!this.$store.getters["userId"]) {
        this.$notify({
          type: "error",
          title: "请先登录"
        });
        return;
      }
      if (this.num > this.pInfo.stock) {
        this.$notify({
          type: "error",
          title: "失败",
          message: "库存不足！"
        });
        return;
      }
      let p;
      if (this.spec) {
        p = JSON.parse(JSON.stringify(this.spec));
        let a = [];
        p.attrs.forEach((e, index, arr) => {
          if (e.values.join(",") == this.label.join(",")) {
            a.push(e);
          }
        });
        p.attrs = a;
        p.attrs.forEach(e => {
          e.detail = JSON.stringify(e.detail);
        });
      }
      await addCart({
        cartNum: this.num,
        productAttrId: 0,
        productId: this.id,
        uid: this.$store.getters["userId"],
        spec: JSON.stringify(p)
      });
      this.$notify({
        title: "成功",
        message: "商品加入购物车成功！",
        type: "success"
      });
      this.$bus.$emit("updataCart");
    },
    chooseItem(index) {
      let p = index;
      if (index == "video") {
        this.$refs.videoPlayer.player.play();
        this.$refs.carousel.setActiveItem(0);
      } else {
        if (this.video) {
          this.$refs.videoPlayer.player.pause();
          this.$refs.carousel.setActiveItem(p + 1);
        } else {
          this.$refs.carousel.setActiveItem(p);
        }
      }
    }
  }
};
</script>
<style>
div.el-carousel__item.is-animating {
  background-color: none !important;
}
.video-js.vjs-fluid,
.video-js.vjs-16-9,
.video-js.vjs-4-3 {
  width: 100%;
  max-width: 100%;
  height: 100%;
}
</style>
<style lang="scss" scoped>
.checked {
  background: #f96868 !important;
  color: #fff !important;
  border-color: #f96868 !important;
}
.proInfo {
  padding: 20px 5%;
  box-sizing: border-box;
  display: flex;
}
.el-carousel__item h3 {
  color: #475669;
  font-size: 18px;
  opacity: 0.75;
  line-height: 300px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}
.product_name {
  font-size: 20px;
  color: #2a333c;
  margin-bottom: 10px;
  text-align: left;
}
.product_price {
  width: 100%;
  padding: 20px;
  background-color: #fafafa;
  color: #f96868;
  text-align: left;
  margin-bottom: 30px;
}
.product_posteg {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  .left_posteg {
    color: #9e9e9e;
    font-size: 15px;
    margin-right: 40px;
    min-width: 40px;
    margin-bottom: 10px;
  }
}
.shopdiscuount {
  border: 1px solid #e4eaec;
  color: #76838f;
  padding: 3px;
  margin-left: 8px;
  cursor: pointer;
  margin-bottom: 10px;
}
.shopdiscuount_active {
  border: 1px solid #f2a654;
  color: #f2a654;
  padding: 3px;
}
.shopdiscuount_active:hover {
  color: #fff;
  background-color: #f2a654;
  border-radius: 2px;
}
.picDetail {
  padding: 10px 5%;
  .detail_tezt {
    color: #62a8ea;
    font-size: 15px;
    width: 100%;
    text-align: left;
    margin-bottom: 20px;
  }
}
</style>